<template>
  <div class="table-classic-wrapper">
    <el-card class="card_box">

      <!-- 查询栏 -->
      <el-form
          :inline="true"
          label-width="90px"
          class="search-form">

        <el-form-item>
          <el-button type="warning" @click="paySelectedOrder" :disabled="JSON.stringify(multipleSelection)==='[]'">
            一键下单
          </el-button>
        </el-form-item>

        <el-form-item>
          <el-button type="danger" @click="deleteSelectedOrder" :disabled="JSON.stringify(multipleSelection)==='[]'">
            一键删除
          </el-button>
        </el-form-item>

      </el-form>

      <!--购买记录表格-->
      <el-table
          :data="shoppingCartList"
          stripe
          :header-cell-style="{textAlign: 'center'}"
          @selection-change="handleSelectionChange"
          :cell-style="{textAlign: 'center'}"
          style="width: 100%">

        <el-table-column type="selection" width="50"/>

        <el-table-column
            prop="picture"
            label="美食图片"
            align="center">
          <template slot-scope="scope">
            <el-image
                style="width: 40px; height: 40px"
                :src="handlerImg(scope.row.picture)"
                fit="fill"></el-image>
          </template>
        </el-table-column>

        <el-table-column
            prop="text"
            label="美食名称">
        </el-table-column>

        <el-table-column
            prop="type"
            label="美食类别"
            align="center">
        </el-table-column>

        <el-table-column
            prop="price"
            label="美食价格"
            align="center">
        </el-table-column>

        <el-table-column
            prop="saleCount"
            label="库存"
            align="center">
        </el-table-column>

        <el-table-column
            prop="historicalSaleCount"
            label="历史销量"
            align="center">
        </el-table-column>

        <el-table-column
            prop="productState"
            label="美食状态"
            align="center">
          <template slot-scope="scope">
            <el-tag type='info' effect="dark" v-if="scope.row.productState===0">在售</el-tag>
            <el-tag type='warning' effect="dark" v-if="scope.row.productState===1">已下架</el-tag>
          </template>
        </el-table-column>

        <el-table-column
            prop="purchaseCount"
            label="购买数量"
            align="center">
          <template slot-scope="scope">
<!--            <el-input-number-->
<!--                v-model="scope.row.purchaseCount"-->
<!--                size="mini" :min="1" :max="scope.row.saleCount"-->
<!--                @change="handleChange(scope)" :disabled="isDisabled(scope)">-->
<!--            </el-input-number>-->
            <span>{{scope.row.purchaseCount}}</span>
          </template>
        </el-table-column>

        <el-table-column
            width="100px"
            label="总价">
          <template slot-scope="scope">
            {{ scope.row.totalPrice | numFilter }}
          </template>
        </el-table-column>

        <el-table-column
            width="100px"
            label="加入日期">
          <template slot-scope="scope">
            {{ format(new Date(scope.row.gmtCreate)) }}
          </template>
        </el-table-column>


        <el-table-column
            width="200px"
            label="操作"
            align="center">

          <template slot-scope="scope">
            <el-button type="primary" size="mini" :disabled="isDisabled(scope)" @click="purchaseNow(scope.row)">购买
            </el-button>

            <el-divider direction="vertical"></el-divider>

            <el-popconfirm title="确定删除该记录？" @confirm="deleteTheOrder(scope.row)">
              <el-button type="danger" size="mini" slot="reference">删除</el-button>
            </el-popconfirm>

          </template>

        </el-table-column>
      </el-table>

      <!--分页-->
      <Pagination :total="total" :page="currentPage" :limit="pageSize" @pagination="handlePageChange"></Pagination>
    </el-card>

    <!--购买对话框-->
    <el-dialog
        title="购 买"
        :visible.sync="dialogVisiblePurchaseNow"
        width="40%"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :before-close="handleClose">
      <div style="">
        <h3>订单信息</h3>

        <el-card shadow="hover" style="padding: 0; min-height: 100px;">

          <el-row>
            <el-col :span="4">
              <strong>美食名称</strong>
            </el-col>

            <el-col :span="20">
              <span>{{ purchaseList.text }}</span>
            </el-col>
          </el-row>

          <el-row style="margin-top: 10px">
            <el-col :span="4">
              <strong>美食价格</strong>
            </el-col>

            <el-col :span="6">
              <span>￥{{ purchaseList.price }}</span>
            </el-col>
          </el-row>

          <el-row style="margin-top: 10px">
            <el-col :span="4">
              <strong>购买数量</strong>
            </el-col>

            <el-col :span="6">
              <span>{{ purchaseList.purchaseCount }}</span>
            </el-col>
          </el-row>

          <el-row style="margin-top: 10px">
            <el-col :span="4">
              <strong>用户积分</strong>
            </el-col>

            <el-col :span="6">
              <span>{{ user.integral }}</span>
            </el-col>
          </el-row>
        </el-card>
      </div>

      <div style="margin-left: 20px;margin-top: 10px">
        <el-row>
          <el-col :span="3" style="margin-top: 13px">
            <strong style="color: black">配送费</strong>
          </el-col>

          <el-col :span="6">
            <strong style="font-size: 35px;color: #F56C6C">￥{{ purchaseList.delivery | numFilter}}</strong>
          </el-col>

        </el-row>

        <el-row>

          <el-col :span="3" style="margin-top: 13px">
            <strong style="color: black">支付金额</strong>
          </el-col>

          <el-col :span="6">
            <strong style="font-size: 35px;color: #F56C6C">￥{{ purchaseList.totalPrice | numFilter }}</strong>
          </el-col>

          <el-col :span="6" style="margin-top: 13px">
            <strong style="color: black">积分抵扣后应支付金额</strong>
          </el-col>

          <el-col :span="8">
            <strong style="font-size: 35px;color: #F56C6C">￥{{ purchaseList.sumMinusIntegral | numFilter }}</strong>
          </el-col>

        </el-row>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-popconfirm title="确定支付该订单吗？" @confirm="payTheOrder">
          <el-button type="primary" slot="reference">确定支付</el-button>
        </el-popconfirm>

        <el-button @click="handleClose" style="margin-left: 10px">取 消</el-button>
      </span>
    </el-dialog>

    <!--一键下单对话框-->
    <el-dialog
        title="一键下单"
        :visible.sync="dialogVisiblePaySelectedOrder"
        width="40%"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :before-close="handleClosePaySelectedOrder">
      <div style="">
        <h3>订单信息</h3>

        <el-card shadow="hover" style="padding: 0; min-height: 100px;">

          <el-row style="margin-top: 10px">
            <el-col :span="4">
              <strong>用户积分</strong>
            </el-col>

            <el-col :span="6">
              <span>{{ user.integral }}</span>
            </el-col>
          </el-row>
        </el-card>
      </div>

      <div style="margin-left: 20px;margin-top: 10px">
        <el-row>
          <el-col :span="3" style="margin-top: 13px">
            <strong style="color: black">配送费总额</strong>
          </el-col>

          <el-col :span="6">
            <strong style="font-size: 35px;color: #F56C6C">￥{{ selectedOrderList.delivery | numFilter }}</strong>
          </el-col>
        </el-row>

        <el-row>

          <el-col :span="3" style="margin-top: 13px">
            <strong style="color: black">支付总额</strong>
          </el-col>

          <el-col :span="6">
            <strong style="font-size: 35px;color: #F56C6C">￥{{ selectedOrderList.totalPrice }}</strong>
          </el-col>

          <el-col :span="6" style="margin-top: 13px">
            <strong style="color: black">积分抵扣后应支付总额</strong>
          </el-col>

          <el-col :span="8">
            <strong style="font-size: 35px;color: #F56C6C">￥{{ selectedOrderList.sumMinusIntegral }}</strong>
          </el-col>

        </el-row>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-popconfirm title="确定支付该订单吗？" @confirm="confirmPaySelectedOrder">
          <el-button type="primary" slot="reference">确定支付</el-button>
        </el-popconfirm>

        <el-button @click="handleClosePaySelectedOrder" style="margin-left: 10px">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/component/pagination/Pagination";
import {getUserInformation} from "@/api/user";
import {getGeneralUserById} from "@/api/general/userGeneral";
import {selectAllCartByUserId, comprehensivePurchaseCommodityCart, payMoney, deletePurchaseById} from "@/api/user/cart/cart";
import {getFee, getWeatherInformation} from "@/api/weather";

export default {

  name: "ShoppingCart",

  components: {
    Pagination
  },

  data() {
    return {
      /**
       * 购买商品的用户信息
       */
      user: undefined,

      /**
       * 购买物品的信息列表
       */
      purchaseList: {
        merchantId: '',
        purchaseId: '',
        text: '',
        tradingWay: '',
        price: 0,
        purchaseCount: 0,
        totalPrice: 0,
        delivery: 0,//配送费
        sumMinusIntegral: 0,//积分抵扣后支付总金额
      },

      /**
       * 一键下单商品信息
       */
      selectedOrderList: {
        totalPrice: 0,
        sumMinusIntegral: 0,//积分抵扣后支付总金额
        delivery: 0,//配送费总额
      },

      /**
       * 购买对话框的显示
       */
      dialogVisiblePurchaseNow: false,

      /**
       * 一键下单对话框的显示
       */
      dialogVisiblePaySelectedOrder: false,

      /**
       * 多选数据暂存数组
       */
      multipleSelection: [],

      total: 0,//商品总数
      currentPage: 0,//当前页码
      pageSize: 6,//每页显示条数

      /**
       * 用户购物车信息列表
       */
      shoppingCartList: [],

      /**
       * 当前天气
       */
      weather: null,

      /**
       * 对应天气所需的配送费
       */
      delivery: '',
    }
  },

  created() {
    this.weather = getWeatherInformation();

    this.delivery = parseInt(getFee(this.weather));

    this.getGeneralUserById()
  },
  filters: {

    numFilter(value) {
      // 截取当前数据到小数点后两位
      return parseFloat(value).toFixed(2)
    }

  },
  methods: {
    /**
     * 获取当前用户购物车中全部商品信息
     */
    getShoppingRecordList() {

      const formData = new FormData();

      formData.append("userId", this.user.id);
      formData.append("currentPage", this.currentPage);
      formData.append("pageSize", this.pageSize);

      selectAllCartByUserId(formData).then(res => {
        this.shoppingCartList = res.message;
        this.total = res.total;
      }).catch(() => {
        this.$message({
          message: "error",
          type: "error"
        })
      })

      // this.axios.get("/shoppingCartList",{
      // }).then(res => {
      //   this.shoppingCartList = res.data.data.records
      // })
    },

    /**
     * 获得用户信息
     */
    getGeneralUserById() {
      const user = eval('(' + getUserInformation() + ')');

      const formData = new FormData();

      formData.append("id", user.id);

      getGeneralUserById(formData).then(res => {
        this.user = res.user;
        this.getShoppingRecordList();
      }).catch(() => {
        this.$message.error("用户信息获取失败");
      })
    },

    /**
     * 根据美食状态判断是否能购买
     * productState--0--在售；1--已下架
     */
    isDisabled(scope) {
      return scope.row.productState !== 0;

    },

    /**
     * 计数器改变的触发方法
     */
    handleChange(scope) {
      scope.row.totalPrice = scope.row.purchaseCount * scope.row.price
    },

    /**
     * 多选操作，与multipleSelection相对应
     */
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    /**
     * 购买对话框的关闭事件
     */
    handleClose() {
      this.dialogVisiblePurchaseNow = false;
    },

    /**
     * 一键下单对话框的关闭事件
     */
    handleClosePaySelectedOrder() {
      this.dialogVisiblePaySelectedOrder = false;
    },

    /**
     * 立即支付按钮click事件,弹出支付界面
     */
    purchaseNow(row) {
      this.purchaseList.merchantId = row.merchantId;
      this.purchaseList.purchaseId = row.id;
      this.purchaseList.text = row.text;
      this.purchaseList.price = row.price;
      this.purchaseList.purchaseCount = row.purchaseCount;
      this.purchaseList.delivery = this.delivery;
      this.purchaseList.totalPrice = row.totalPrice + this.purchaseList.delivery;
      this.purchaseList.sumMinusIntegral = this.purchaseList.totalPrice - Math.floor(this.user.integral / 100);
      this.dialogVisiblePurchaseNow = true;
    },

    /**
     * 一键下单按钮click事件,弹出一键下单界面
     */
    paySelectedOrder() {
      let totalPrice = 0;
      let delivery = 0;

      for (let i = 0; i < this.multipleSelection.length; i++) {
        let purchaseCount = this.multipleSelection[i].purchaseCount;
        let price = this.multipleSelection[i].price;

        totalPrice = totalPrice + purchaseCount * price + this.delivery;
        delivery += this.delivery;
      }

      this.selectedOrderList.totalPrice = totalPrice;
      this.selectedOrderList.sumMinusIntegral = totalPrice - Math.floor(this.user.integral / 100);
      this.selectedOrderList.delivery = delivery;

      this.dialogVisiblePaySelectedOrder = true;
    },

    /**
     * 确定支付（下单一个商品）
     */
    payTheOrder() {
      if (this.user.balance < this.purchaseList.sumMinusIntegral) {
        this.$message.warning("余额不足，无法进行支付");
      } else {
        let order = {
          id: this.purchaseList.purchaseId,
          purchaseCount: this.purchaseList.purchaseCount,
          delivery: this.purchaseList.delivery
        }
        let data = []
        data.unshift(order)
        this.selectCommodity(data, this.purchaseList.totalPrice)
      }
    },

    /**
     * 一键下单被选中的商品
     */
    confirmPaySelectedOrder() {
      if (this.user.balance < this.selectedOrderList.sumMinusIntegral) {
        this.$message.warning("余额不足，无法进行支付");
      } else {
        let data = []
        this.multipleSelection.forEach(order => {
          let o = {
            id: order.id,
            purchaseCount: order.purchaseCount,
            delivery: this.delivery
          }
          data.unshift(o)
        })
        this.selectCommodity(data, this.selectedOrderList.totalPrice)
      }
    },

    /**
     * 选择商品下单
     */
    selectCommodity(data, totalPrice){
      comprehensivePurchaseCommodityCart(data).then(res => {
        if (res.information === 0) {
          this.$message.error("商品《" + res.text + "》库存不足，无法进行支付");
        } else if (res.information === 1) {
          this.pay(totalPrice)
          this.dialogVisiblePurchaseNow = false;
          this.dialogVisiblePaySelectedOrder = false;
        }
      }).catch(() => {
        this.$message.error("error");
      })
    },

    /**
     * 支付
     */
    pay(totalPrice){
      let user = {
        id: this.user.id,
        balance: totalPrice
      }
      payMoney(user).then(res => {
        if(res.message === 1){
          this.$message.success("购买成功")
          this.getGeneralUserById()
        }
      })
    },

    /**
     * 一键删除被选中的记录
     */
    deleteSelectedOrder() {
      for (let i = 0; i < this.multipleSelection.length; i++) {
        this.deleteOneOrder(this.multipleSelection[i]);
      }
    },

    /**
     * 删除记录
     */
    deleteTheOrder(row) {
      const formData = new FormData();

      formData.append("purchaseId", row.id);

      deletePurchaseById(formData).then(res => {
        if (res.delete === 1) {
          this.$message.success("删除商品《" + res.text + "》成功");
          this.getShoppingRecordList();
        }
      }).catch(() => {
        this.$message.error("error");
      })
    },

    /**
     * 一个一个地删除购物车中的记录
     */
    deleteOneOrder(purchase) {
      const formData = new FormData();

      formData.append("purchaseId", purchase.id);

      deletePurchaseById(formData).then(res => {
        if (res.delete === 1) {
          this.$message.success("删除商品《" + res.text + "》成功");
          this.getShoppingRecordList();
        }
      }).catch(() => {
        this.$message.error("error");
      })
    },

    /**
     * 处理分页
     */
    handlePageChange(val) {
      this.currentPage = val.page;
      this.getShoppingRecordList();
    },

    /**
     * 展示图片
     */
    handlerImg(picture) {
      console.log("data:image/jpeg;base64," + picture)
      return "data:image/jpeg;base64," + picture
    },

    /**
     * 修改加入购物车日期格式
     */
    format(date) {
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var day = date.getDate();
      var hour = date.getHours();
      var minute = date.getMinutes();
      var second = date.getSeconds();

      if (month < 10) {
        month = '0' + month;
      }

      if (day < 10) {
        day = '0' + day;
      }

      if (hour < 10) {
        hour = '0' + hour;
      }

      if (minute < 10) {
        minute = '0' + minute;
      }

      if (second < 10) {
        second = '0' + second;
      }

      return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
    },
  }
}
</script>

<style scoped>
.card_box {
  height: 75vh;
  margin: 5px 5px;
}
</style>
